package com.putong35.common.utils;


import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.SubscriptSpan;
import android.text.style.SuperscriptSpan;
import android.text.style.TextAppearanceSpan;
import android.text.style.TypefaceSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

public class CharSpanUtil {

	public CharSpanUtil() {
		// TODO Auto-generated constructor stub
	}


	/**
	 * 给文本添加下划线，并且可以设置点击之后的动作。
	 * TextView.setMovementMethod(LinkMovementMethod.getInstance());
	 * 
	 * @param str
	 *            目标文本
	 * @param listener
	 *            点击文本之后的action
	 * @return
	 */
	public static SpannableString setTextUnderline(CharSequence str, int start, int end,
			ClickableSpan listener) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

		if (listener != null) {
			ss.setSpan(listener, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		}
		return ss;
	}


	/**
	 * 设置字体(default,default-bold,monospace,serif,sans-serif)
	 * 
	 * @param str
	 * @param typeface
	 *            字体类型 e.g Typeface.MONOSPACE, Typeface.SERIF
	 * @return
	 */
	public static SpannableString setTextTypeface(CharSequence str, int start, int end, String family) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new TypefaceSpan(family), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		return ss;
	}


	/**
	 * 设置字体样式（正常，粗体，斜体，粗斜体：Typeface.NORMAL,Typeface.BOLD,Typeface.ITALIC,Typeface.BOLD_ITALIC）
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param style
	 * @return
	 */
	public static SpannableString setTextStyle(CharSequence str, int start, int end, int style) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new StyleSpan(style), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		return ss;
	}


	/**
	 * 设置字符串中子串的文本大小
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param value
	 * @param isDip
	 *            value值是否是dip为单位
	 * @return
	 */
	public static SpannableString setTextSize(CharSequence str, int start, int end, int value, boolean isDip) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end + " string length == " + str.length());
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new AbsoluteSizeSpan(value, isDip), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); // AbsoluteSizeSpan第二个参数代表value是不是dip值
		return ss;
	}


	/**
	 * 字符串子串缩小或放大
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param value
	 *            if(value < 1.0) 缩小文本 else 放大文本
	 * @return
	 */
	public static SpannableString scaleTextSize(CharSequence str, int start, int end, float value) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new RelativeSizeSpan(value), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); // value ==
																								// 0.5f表示默认字体大小的一半
		return ss;
	}


	/**
	 * 设置子串的前景色
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param color
	 *            Color.MAGENTA 或者 Color.parseColor("#ff0000")
	 * @return
	 */
	public static SpannableString setTextForegroundColor(CharSequence str, int start, int end, int color) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		return ss;
	}


	/**
	 * 设置子串的背景色
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param color
	 *            Color.MAGENTA 或者 Color.parseColor("#ff0000")
	 * @return
	 */
	public static SpannableString setTextBackgroundColor(CharSequence str, int start, int end, int color) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new BackgroundColorSpan(color), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		return ss;
	}


	/**
	 * 设置删除线
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static SpannableString setTextStrikethrough(CharSequence str, int start, int end) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new StrikethroughSpan(), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		return ss;
	}


	/**
	 * 将某个子串格式化成上标或者下标
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param isSub
	 * @return
	 */
	public static SpannableString setTextScript(CharSequence str, int start, int end, boolean isSub) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		if (isSub) {
			ss.setSpan(new SubscriptSpan(), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		} else {
			ss.setSpan(new SuperscriptSpan(), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		}
		return ss;
	}


	/**
	 * 设置超级链接
	 * 注意：需要添加setMovementMethod方法附加响应
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @param url
	 *            邮件："mailto:webmaster@google.com"
	 *            网络："http://www.baidu.com"
	 *            短信："sms:4155551212" sms:或者smsto
	 *            彩信："mms:4155551212" mms:或者mmsto:
	 *            地图："geo:38.899533,-77.036476"
	 * @return
	 */
	public static SpannableString setTextUrl(CharSequence str, int start, int end, String url) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ss.setSpan(new URLSpan(url), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		return ss;
	}


	/**
	 * 设置字体（依次包括字体名称，字体样式，字体大小，字体颜色，链接颜色）
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 * @example "monospace", android.graphics.Typeface.BOLD_ITALIC, 30, csl,
	 *          csllink), 51, 53, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
	 */
	public static SpannableString setTextAppearance(Context context, CharSequence str, int start, int end,
			String family, int style, int size, int colorRes, int linkColorRes) {
		if (start < 0 || start >= str.length() || end > str.length()) {
			throw new RuntimeException("文本处理越界 start == " + start + " end == " + end);
		}
		final SpannableString ss = new SpannableString(str);
		ColorStateList textColorList = null;
		XmlResourceParser xppcolor = context.getResources().getXml(colorRes);
		try {
			textColorList = ColorStateList.createFromXml(context.getResources(), xppcolor);
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		ColorStateList linkedColorList = null;
		XmlResourceParser xpplinkcolor = context.getResources().getXml(linkColorRes);
		try {
			linkedColorList = ColorStateList.createFromXml(context.getResources(), xpplinkcolor);
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ss.setSpan(new TextAppearanceSpan(family, style, size, textColorList, linkedColorList), start, end,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		return ss;
	}


	private void test(final Context context, TextView view) {
		int length = 3;
		String str = "111222333444555666777888999000aaaaaabbb";
		int start = 0;
		int end = start + length;

		SpannableString spanStr = CharSpanUtil.setTextSize(str, start, end, 30, false);
		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextSize(spanStr, start, end, 30, true);

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextBackgroundColor(spanStr, start, end, Color.parseColor("#ff0000"));

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextForegroundColor(spanStr, start, end, Color.parseColor("#ff0000"));

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextUrl(spanStr, start, end, "http://www.baidu.com");

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextScript(spanStr, start, end, true);

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextStrikethrough(spanStr, start, end);

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextStyle(spanStr, start, end, Typeface.BOLD_ITALIC);

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextTypeface(spanStr, start, end, "serif");

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextTypeface(spanStr, start, end, "sans-serif");

		start = end;
		end += length;
		spanStr = CharSpanUtil.setTextUnderline(spanStr, start, end, new ClickableSpan() {

			@Override
			public void onClick(View widget) {
				Toast.makeText(context, "wahahahah", Toast.LENGTH_LONG).show();

			}

		});

		start = end;
		end += length;
/*		spanStr = CharSpanUtil.setTextAppearance(context, spanStr, start, end, "sans-serif",
				Typeface.BOLD_ITALIC, 40, R.color.color_text_states, R.color.color_text_linked_states);
*/
		view.append(spanStr);
		view.setMovementMethod(LinkMovementMethod.getInstance());

	}

}
